package com.jhs.kjs.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.jhs.kjs.dto.MenuDTO;
import com.jhs.kjs.dto.MenuPagingDTO;
import com.jhs.kjs.handler.exception.AldangMessegeException;
import com.jhs.kjs.service.IAdminMenuService;

@RequestMapping(value = "/admin")
@Controller
public class AdminMenuController extends CommonController {

	@Autowired
	IAdminMenuService adminMenuService;


	@RequestMapping(value = "/adminMenuMain", method = { RequestMethod.GET,
			RequestMethod.POST })
	public ModelAndView adminMenuMain() {
		ModelAndView mav = new ModelAndView("admin/menu_list");
		List<MenuDTO> menuList = adminMenuService.getAllMenuList();
		mav.addObject("menuList", menuList);
		setTotalPage(mav);
		return mav;
	}

	@RequestMapping(value = "/adminMenuWrite", method = { RequestMethod.GET,
			RequestMethod.POST })
	public ModelAndView adminMenuWrite(@ModelAttribute("param") MenuDTO param) {
		ModelAndView mav = new ModelAndView("admin/menu_write");
		MenuDTO menu = adminMenuService.getMenuByMenuIndex(param);
		List<MenuDTO> menuList = adminMenuService.getAllMenuList();
		mav.addObject("menuList", menuList);
		mav.addObject("menu", menu);
		return mav;
	}



	@RequestMapping(value = "/getAdminMenuList", method = {	RequestMethod.POST })
	public ModelAndView getAdminMenuList(@ModelAttribute("param") MenuPagingDTO param) {
		ModelAndView mav = new ModelAndView("admin/menu_write");

		List<MenuDTO> menuList = adminMenuService.getMenuPagingList(param);
		setTotalPage(mav, param);
		mav.addObject("menuTbl", menuList);
		return mav;
	}



	@RequestMapping(value = "/getAdminMenuUpdate", method = {	RequestMethod.POST })
	public ModelAndView getAdminMenuUpdate(HttpServletRequest request, @ModelAttribute("param") MenuPagingDTO param) {
		if(getUser(request).getLevel()<40) throw new AldangMessegeException("관리자가 아님");// 보안 처리.
		
		ModelAndView mav = new ModelAndView();
		if(param.getMenuIndex()!=null && param.getMenuIndex()>0){
			adminMenuService.updateMenu(param);
		}else{
			adminMenuService.insertMenu(param);
		}
		mav.addObject("result", "등록되었습니다.");
		return mav;
	}

	
	

	private void setTotalPage(ModelAndView mav) {
		int totalCnt = adminMenuService.getTotalCount();
		mav.addObject("totalPage", totalCnt);
		
	}

	private void setTotalPage(ModelAndView mav, MenuDTO menu) {
		mav.addObject("totalPage", adminMenuService.getTotalCountWithSearchValue(menu));
		
	}
}

